<template>
  <div class="app-container">
    <div class="head">
      <img src="@/assets/img/Layout/position.png" />
      <p class="see-block">客户数据下发新建</p>
    </div>
    <div class="view-container">
      <el-row class="status-title">
        <el-col class="mr20 width100">
          <el-button
            class="btn-success width100"
            type="primary"
            @click="submitForm()"
          >确定执行</el-button>
        </el-col>
      </el-row>
      <el-form ref="form" :model="form" label-width="140px" class="mt30">
        <el-row>
          <el-col :span="8">
            <el-form-item label="编码:">
              <el-input placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="下发类型:" prop="dataType">
              <el-select v-model="dataType" style="width:100%;" placeholder="请选择">
                <el-option label="客户下发" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="选择公司组织:">
              <el-select v-model="organizationDepts" style="width:100%;" multiple placeholder="请选择" value-key="id" @change="getSysDepts" clearable>
                <el-option
                  v-for="item in organizationList"
                  :key="item.id"
                  :label="item.orgName"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户类型:" prop="customerType">
              <el-select v-model="customerType" style="width:100%;" placeholder="请选择">
                <el-option label="企业客户" value="1"></el-option>
                <el-option label="会员客户" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择客户:">
              <el-button
                class="btn-default"
                type="primary"
                @click="onClickLayer"
              >选择客户</el-button>
              <div v-for="item in ids" :key="item.id">
                {{ item.code + '-' + item.name }}
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(item)"
                ></el-button>
              </div>
              <div v-for="item in memberIds" :key="item.memberInformationId">
                {{ item.phone + '-' + item.nickName }}
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteMember(item)"
                ></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 客户弹出对话框 -->
    <el-dialog title="客户" :visible.sync="open" width="90%" top="50px" append-to-body center>
      <el-row class="mb8">
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="el-icon-sort"
            size="mini"
            @click="toggleExpandAll"
          >展开/折叠</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-table v-if="refreshTable" v-loading="loading" :data="userList" row-key="sortId"
            :default-expand-all="isExpandAll"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="sortName" label="分类名称" width="150">
              <template slot-scope="scope">
                <span @click="handleItem(scope.row)" style="cursor:pointer">{{ scope.row.sortName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sortCode" label="分类编码" align="center"></el-table-column>
          </el-table>
        </el-col>
        <el-col :span="1">
          <div class="line-layer"></div>
        </el-col>
        <el-col :span="17">
          <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
            <el-form-item prop="searchValue">
              <el-input
                v-model="queryParams.searchValue"
                placeholder="名称或者编码模糊查询"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="loading" :data="customerList" ref="materialTable" @selection-change="handleSelectionChange" :row-key="getRowKeys">
            <el-table-column type="selection" width="35" align="center" :reserve-selection="true" />
            <el-table-column label="序号" type="index" align="center" width="50">
              <template slot-scope="scope">
                <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column label="编码" align="center" prop="code" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="简称" align="center" prop="abbreviation"  :show-overflow-tooltip="true" />
            <el-table-column label="销售区域" align="center" prop="salesAreaName" :show-overflow-tooltip="true" />
            <el-table-column label="币种" align="center" prop="currency" :show-overflow-tooltip="true" />
            <el-table-column label="联系人" align="center" prop="contact" :show-overflow-tooltip="true" />
            <el-table-column label="付款条件" align="center" prop="paymentTerms" :show-overflow-tooltip="true" />
            <el-table-column label="创建者" align="center" prop="createBy" />
            <el-table-column value-format="yyyy-MM-dd" label="创建日期" align="center" prop="createTime" width="180px" />
            <el-table-column label="审核状态" align="center" prop="approvalStatus">
              <template slot-scope="scope">
                <div v-if="scope.row.approvalStatus == 0" style="color:#13C2C2"></div>
                <div v-if="scope.row.approvalStatus == 1" style="color:#13C2C2">待审核</div>
                <div v-if="scope.row.approvalStatus == 2" style="color:#52C41A">已审核</div>
                <div v-if="scope.row.approvalStatus == 3" style="color:#fd562c">拒绝</div>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <div v-if="scope.row.status == 0" style="color:#13C2C2">禁用</div>
                <div v-if="scope.row.status == 1" style="color:#52C41A">正常</div>
              </template>
            </el-table-column>
            <el-table-column label="最后更新" align="center" prop="updateBy" />
            <el-table-column value-format="yyyy-MM-dd" label="更新日期" align="center" prop="updateTime" width="180px" />
            <template v-for="(a, index) in organizationList">
              <el-table-column :label="a.orgName" prop="deptList" align="center" :key="index" width="200">
                <template slot-scope="scope">
                  <template v-for="item in  scope.row.deptList">
                    <template v-if="item">
                      <template v-if="item.deptId == a.deptId">
                        <el-checkbox :value="true" :key="item.deptId" disabled class="on-checked" ></el-checkbox>
                      </template>
                    </template>
                  </template>
                </template>
              </el-table-column>
            </template>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="handleItem()"
          />
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 会员弹出对话框 -->
    <el-dialog title="会员" :visible.sync="memberOpen" width="80%" top="50px" append-to-body center>
      <el-row>
        <el-col :span="24">
          <el-form :model="queryParamsMember" ref="queryFormMember" :inline="true" @submit.native.prevent>
            <el-form-item label="手机号" prop="phone">
                <el-input
                    v-model="queryParamsMember.phone"
                    placeholder="会员手机号检索"
                    size="small"
                    maxlength="11"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryMember" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQueryMember" class="list-search">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionMember" :row-key="getRowKeysMember" ref="materialTableMember">
            <el-table-column type="selection" width="35" align="center" :reserve-selection="true" />
              <el-table-column label="序号" type="index" align="center" width="50">
                  <template slot-scope="scope">
                      <span>{{(queryParamsMember.pageNum - 1) * queryParamsMember.pageSize + scope.$index + 1}}</span>
                  </template>
              </el-table-column>
              <el-table-column label="手机号"  align="center" prop="phone" />
              <el-table-column label="呢称" align="center" prop="nickName" />
              <el-table-column label="性别" align="center" prop="sex" />
              <el-table-column label="生日" align="center" prop="dateOfBirth" />
              <el-table-column label="学历" align="center" prop="education" />
              <el-table-column label="备注" align="center" prop="remarks" />
              <el-table-column label="最近一次登录" align="center" prop="lastLoginTime" />
              <el-table-column label="状态" align="center" prop="status">
                  <template slot-scope="scope">
                      <div v-if="scope.row.status == '1'">待审核</div>
                      <div v-if="scope.row.status == '2'">已审核</div>
                      <div v-if="scope.row.status == '3'">拒绝</div>
                  </template>
              </el-table-column>
          </el-table>
          <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParamsMember.pageNum"
              :limit.sync="queryParamsMember.pageSize"
              @pagination="getMemberList"
          />
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { addDataReleased, addMemberDataReleased } from "@/api/system/basedata/dataReleased/dataReleased"
import { organizationList } from "@/api/system/organization/organization"
import { listUserList } from "@/api/system/basedata/userlist/userlist"
import { listUser } from "@/api/system/basedata/user/user"
import { memberList } from "@/api/system/member/member"

export default {
  name: "add",
  data(){
    return {
      form: {
        dataIds: [],
        dataType: '', // 下发类型
        sysDepts: [], // 选中组织数据
      },
      dataType: '3', // 下发类型
      dataUserId: [],
      customerType: '1', // 客户类型
      organizationDepts: [],
      organizationList: [], // 公司组织列表
      open: false,
      loading: true,
      userList: [],
      isExpandAll: true,
      refreshTable: true,
      // 客户列表
      customerList: [],
      // 查询参数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerSortId: undefined,
        status : 1,
        approvalStatus: 2,
        searchValue: undefined
      },
      queryParamsMember: {
        pageNum: 1,
        pageSize: 10,
        phone: '', // 手机号
        status: 2,
      },
      // 会员列表
      memberList: [],
      memberOpen: false,
      ids: [],
      memberIds: [],
      dataMemberId: []
    }
  },
  created() {
    this.getOrganizationList()
  },
  methods: {
    // 获取公司组织列表
    getOrganizationList() {
        organizationList({status: 0}).then(res => {
          this.organizationList = res.rows
        })
    },
    // 选中数据结构转换
    getSysDepts(e){
      let arr = []
      e.forEach(i => {
        let obj = {
          deptId: i.deptId,
          deptName: i.orgName
        }
        arr.push(obj)
      })
      this.form.sysDepts = arr
    },
    // 客户弹窗显示
    onClickLayer(){
      if(this.customerType == '1'){
        this.open = true
        this.handleItem()
        this.getUserList()
      }else if(this.customerType == '2'){
        this.memberOpen = true
        this.getMemberList()
      }
    },
    // 获取客户列表
    getUserList() {
      this.loading = true
      listUserList().then(res => {
        this.userList = this.handleTree(res.data, "sortId")
        this.loading = false
      })
    },
    // 转换客户分类数据结构 
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.sortId,
        label: node.sortName,
        children: node.children
      }
    },
    // 展开/折叠
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    // 根据分类查看客户
    handleItem(item){
      // console.log(item)
      if(item !== undefined){
        this.queryParams.customerSortId = item.sortId
      }
      listUser(this.addDateRange(this.queryParams)).then(res => {
        this.customerList = res.rows
        this.total = res.total
      })
    },
    // 获取会员列表
    getMemberList() {
      this.loading = true
      memberList(this.addDateRange(this.queryParamsMember)).then(res => {
          this.memberList = res.rows
          this.total = res.total
          this.loading = false
      })
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.handleItem()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 会员搜索
    handleQueryMember(){
      this.queryParamsMember.pageNum = 1
      this.getMemberList()
    },
    // 会员重置按钮
    resetQueryMember(){
      this.resetForm("queryFormMember")
      this.handleQueryMember()
    },
    // 翻页不清空
    getRowKeys(row){
      return row.id
    },
    getRowKeysMember(row){
      return row.memberInformationId
    },
    // 选中客户
    handleSelectionChange(row){
      this.ids = row.map(item => item)
      this.form.dataIds = this.ids.map(id => id.id)
      this.dataUserId = this.ids.map(id => id.id)
    },
    // 选中会员
    handleSelectionMember(row){
      this.memberIds = row.map(item => item)
      this.form.dataIds = this.memberIds.map(id => id.memberInformationId)
      this.dataMemberId = this.memberIds.map(id => id.memberInformationId)
    },
    // 删除客户
    handleDelete(item){
      let index = this.ids.findIndex(i => {
        return i.id == item.id
      })
      this.dataUserId.splice(index, 1)
      // 清除当前选中客户
      this.customerList.find(y => {
        if(item.id == y.id){
          this.$refs.materialTable.toggleRowSelection(y, false)
        }
      })
    },
    // 删除会员
    handleDeleteMember(item){
      let index = this.memberIds.findIndex(i => {
        return i.memberInformationId == item.memberInformationId
      })
      this.dataMemberId.splice(index, 1)
      // 清除当前选中客户
      this.memberList.find(y => {
        if(item.memberInformationId == y.memberInformationId){
          this.$refs.materialTableMember.toggleRowSelection(y, false)
        }
      })
    },
    // 提交数据
    submitForm() {
      if(this.form.sysDepts.length == 0){
        this.$modal.msgError('请选择公司组织！')
      }else if(this.form.dataIds.length == 0){
        this.$modal.msgError('请选择客户！')
      }else{
        if(this.dataUserId.length > 0 && this.dataMemberId.length > 0){
          addDataReleased({ dataIds: this.dataUserId, dataType: '3', sysDepts: this.form.sysDepts }).then(res => {
            if(res.code == 200){
                addMemberDataReleased({ dataIds: this.dataMemberId, dataType: '5', sysDepts: this.form.sysDepts }).then(res => {
                  this.$tab.closeOpenPage({ path: "/basedata/user/dataReleased" })
                  this.$modal.msgSuccess("下发成功！")
                })
            }
          })
        }else if(this.dataUserId.length > 0 && this.dataMemberId.length == 0){
          addDataReleased({ dataIds: this.dataUserId, dataType: '3', sysDepts: this.form.sysDepts }).then(res => {
            if(res.code == 200){
              this.$tab.closeOpenPage({ path: "/basedata/user/dataReleased" })
              this.$modal.msgSuccess("下发成功！")
            }
          })
        }else if(this.dataUserId.length == 0 && this.dataMemberId.length > 0){
          addMemberDataReleased({ dataIds: this.dataMemberId, dataType: '5', sysDepts: this.form.sysDepts }).then(res => {
            this.$tab.closeOpenPage({ path: "/basedata/user/dataReleased" })
            this.$modal.msgSuccess("下发成功！")
          })
        }
      }
    }
  }
}
</script>